package com.ltsw.mvpbaseproject.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import com.ltsw.mvpbaseproject.R;
import com.ltsw.mvpbaseproject.baseView.BaseActivity;
import com.ltsw.mvpbaseproject.presenter.WebPresenter;

public class WebViewActivity extends BaseActivity<WebPresenter> {

    private WebView mWebView;
    private TextView tvTest;

    @SuppressLint("JavascriptInterface")
    @Override
    public void initView() {
        tvTest = findViewById(R.id.test);
        mWebView = (WebView) findViewById(R.id.webView);
        initWebView();
    }

    @Override
    public void initData() {
        tvTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 第一种方法：加载JS方法，该方法没有回调函数
//                mWebView.loadUrl("javascript:testDiv()");
                //第二种方法：加载JS，该方式可以接收JS 返回内容。
                mWebView.evaluateJavascript("javascript:bridgeLog('android传来数据：123123')", new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String value) {
                        //此处为 js 返回的结果
                        Toast.makeText(WebViewActivity.this, "Web端返回数据：" + value, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    @Override
    public WebPresenter getPresenter() {
        return new WebPresenter();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_web_view;
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, WebViewActivity.class);
        context.startActivity(intent);
    }

    public void initWebView() {
        mWebView.getSettings().setTextZoom(100);//禁止网页字体随系统变化
        mWebView.getSettings().setJavaScriptEnabled(true); // 允许JS
        mWebView.getSettings().setDomStorageEnabled(true);// 设置可以使用localStorage
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress < 100) {
                    showLoading();
                } else {
                    hideLoading();
                }
                super.onProgressChanged(view, newProgress);
            }

        });// 允许alert弹出
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);// 禁止缓存
        mWebView.setWebViewClient(new WebViewClient() { // 设置在本软件中跳转
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                mWebView.loadUrl("file:///android_asset/nowifi.html");
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();  // 接受信任所有网站的证书
                // handler.cancel(); // 默认操作 不处理
                // handler.handleMessage(null);// 可做其他处理
            }
        });

        // 屏蔽掉长按事件 因为webview长按时将会调用系统的复制控件:
        mWebView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        mWebView.addJavascriptInterface(WebViewActivity.this, "android");
//        mWebView.loadUrl("http://smartapp.kaifa.zzltsw.com/demo.html");
        mWebView.loadUrl("file:///android_asset/nowifi.html");
    }

    /**
     * 注销webView，放置内存泄漏
     */
    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.clearHistory();
            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView.destroy();
            mWebView = null;
        }
        super.onDestroy();
    }

    @JavascriptInterface
    public void submitFromWeb(String num) {
        Toast.makeText(this, "Web调用Android本地测试方法" +num, Toast.LENGTH_SHORT).show();
    }

    @JavascriptInterface
    public void hdTest() {
        Toast.makeText(this, "Web调用Android本地测试方法2", Toast.LENGTH_SHORT).show();
    }

}
